package dao

import (
	"log"

	"gitee.com/Yu-eng/Myproject/my-go-blog/models"
)

func GetCategoryNameById(cId int) string {
	row, err := DB.Query("select name from blog_category where cid = ?", cId)
	if err != nil {
		log.Println(err)
	}
	//查询到的结果应该是唯一的
	var categoryName string
	//要对row 的结果先进行next 操作才能得到第一行的结果
	row.Next()
	err = row.Scan(&categoryName)
	if err != nil {
		log.Println("getcategorynamebyid row.scan error ", err)
	}
	return categoryName
}

func GetAllCategory() ([]models.Category, error) {
	rows, err := DB.Query("select * from blog_category")
	if err != nil {
		log.Println("GetAllCategory 查询出错:", err)
	}
	//拿到数据 序列化为数据结构
	var categorys []models.Category
	for rows.Next() {
		var category models.Category
		//这里将查询的行 的值赋给category
		err = rows.Scan(&category.Cid, &category.Name, &category.CreateAt, &category.UpdateAt)
		if err != nil {
			log.Println("GetAllCategory rows.scan 出错：", err)
			return nil, err
		}
		categorys = append(categorys, category)
	}
	return categorys, nil
}
